package com.example.eda.consumer;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Component
public class TransactionConsumer {

    @RabbitListener(queues = "tx_queue")
    @Transactional(transactionManager = "transactionManager")
    public void handleMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag)
            throws IOException {

        try {
            // 业务处理逻辑
            System.out.println("Received: " + message);

            // 模拟业务操作
            if(processBusiness(message)) {
                // 确认消息
                channel.basicAck(tag, false);
            } else {
                // 拒绝消息（重回队列）
                channel.basicNack(tag, false, true);
            }
        } catch (Exception e) {
            // 记录日志并拒绝消息
            channel.basicNack(tag, false, false);
            throw new AmqpRejectAndDontRequeueException("Message processing failed", e);
        }
    }

    private boolean processBusiness(String message) {
        // 这里编写你的业务逻辑
        return true; // 返回处理结果
    }
}
